//
//  SearchViewController.m
//  MiaoTu
//
//  Created by dllo on 16/9/13.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "SearchViewController.h"
#import "HotPlaceCollectionCell.h"
#import "ZWYNetTool.h"
#import "Keywords.h"
#import "TravelTableCell.h"
#import "TravelModel.h"
#import "TravelItem.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"
#import "LineDetailViewController.h"
#import "PersonalHomeViewController.h"
#import "ConcernAndFan.h"
#import "UserInfo.h"
#import "SearchPersonTableCell.h"
#import "LoginViewController.h"

#define kHotPlaceCollectionCell @"SearchHotPlaceCollectionCellIdentifier"
#define kTravelTableCell @"TravelTableCellSearchIdentifier"
#define kSearchPersonTableCell @"SearchPersonTableCellIdentifier"

typedef NS_ENUM(NSUInteger, SearchType) {
    SearchTypeYueyou,
    SearchTypeUsers
};

@interface SearchViewController ()
<
    UICollectionViewDataSource,
    UICollectionViewDelegate,
    UITextFieldDelegate,
    UITableViewDataSource,
    UITableViewDelegate,
    TravelTableCellDelegate,
    CLLocationManagerDelegate
>
@property (weak, nonatomic) IBOutlet UILabel *hotPlaceLabel;
@property (weak, nonatomic) IBOutlet UICollectionView *hotCollection;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *fl;
@property (weak, nonatomic) IBOutlet UITextField *searchText;
@property (weak, nonatomic) IBOutlet UIImageView *chooseTriangleImage;
@property (weak, nonatomic) IBOutlet UIView *chooseView;
@property (weak, nonatomic) IBOutlet UILabel *searchTypeLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray<NSString *> *citys;

@property (nonatomic, strong) NSMutableArray<TravelItem *> *travelItemArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) CLLocationManager *locManager;
@property (nonatomic, strong) CLLocation *location;
@property (nonatomic, assign) SearchType searchType;

@property (nonatomic, strong) NSMutableArray<UserInfo *> *userInfoArray;
@end

@implementation SearchViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self createView];
    self.searchType = SearchTypeYueyou;
    
    if (_cityString.length > 0) {
        _searchText.text = _cityString;
        _tableView.hidden = NO;
        [self createTableData];
    }
    [self createData];
}

#pragma mark - View

- (void)createView {
    self.view.backgroundColor = [UIColor colorWithWhite:0.925 alpha:1.000];
    self.fl.itemSize = CGSizeMake(75, 35);
    self.fl.minimumInteritemSpacing = 20;
    self.fl.minimumLineSpacing = 25;
    [_hotCollection registerClass:[HotPlaceCollectionCell class] forCellWithReuseIdentifier:kHotPlaceCollectionCell];

    // tableView
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(createTableData)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerLoadData)];
    [self.tableView registerNib:[UINib nibWithNibName:@"SearchPersonTableCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:kSearchPersonTableCell];
    
    
    [self ceateLocationManager];
}

#pragma mark - Data

- (void)createData {
    NSDictionary *headerDic = @{@"User-Agent":@"Dalvik/1.6.0 (Linux; U; Android 4.3; R6007 Build/JLS36C) Paros/3.2.13", @"Host":@"api.miaotu.net", @"Connection":@"Keep-Alive"};
    [ZWYNetTool GET:@"http://api.miaotu.net/v2/base/search/keywords" andBody:nil andHeader:headerDic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        Keywords *keywords = [Keywords modelWithDic:result];
        self.citys = keywords.Items;
        [self.hotCollection reloadData];
    } andFailureBlock:^(NSError *error) {
        
    }];
}

- (void)createTableData {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = NSLocalizedString(@"加载中", @"data loading");
    hud.minSize = CGSizeMake(150.f, 100.f);
    
    NSDictionary *headerDic = @{@"User-Agent":@"Dalvik/1.6.0 (Linux; U; Android 4.3; R6007 Build/JLS36C) Paros/3.2.13", @"Host":@"api.miaotu.net", @"Connection":@"Keep-Alive"};
    
    NSString *searchTypeString = nil;
    if ([_searchTypeLabel.text isEqualToString:@"线路"]) {
        self.searchType = SearchTypeYueyou;
        searchTypeString = @"yueyou";
    } else if ([_searchTypeLabel.text isEqualToString:@"人"]){
        self.searchType = SearchTypeUsers;
        searchTypeString = @"users";
    } else {
        NSLog(@"除了线路和人之外的东西出现了");
    }
    
    NSString *tocken = [[NSUserDefaults standardUserDefaults] objectForKey:@"tocken"];
    if (tocken.length == 0) {
        tocken = @"";
    }
    NSString *urlString = [NSString stringWithFormat:@"http://api.miaotu.net/v2/%@/search?token=%@&keywords=%@&page=1&num=10", searchTypeString, tocken, _searchText.text];
    [ZWYNetTool GET:urlString andBody:nil andHeader:headerDic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        if (_searchType == SearchTypeYueyou) {
            TravelModel *travelModel = [TravelModel modelWithDic:result];
            self.travelItemArray = travelModel.Items.mutableCopy;
        } else {
            ConcernAndFan *cafModel = [ConcernAndFan modelWithDic:result];
            self.userInfoArray = cafModel.Items.mutableCopy;
        }
        [_tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        _currentPage = 1;
        [hud hideAnimated:YES];
    } andFailureBlock:^(NSError *error) {
        
    }];
}

- (void)footerLoadData {
    _currentPage += 1;
    NSString *searchTypeString = nil;
    if ([_searchTypeLabel.text isEqualToString:@"线路"]) {
        self.searchType = SearchTypeYueyou;
        searchTypeString = @"yueyou";
    } else if ([_searchTypeLabel.text isEqualToString:@"人"]){
        self.searchType = SearchTypeUsers;
        searchTypeString = @"users";
    } else {
        NSLog(@"除了线路和人之外的东西出现了");
    }
    
    NSString *tocken = [[NSUserDefaults standardUserDefaults] objectForKey:@"tocken"];
    if (tocken.length == 0) {
        tocken = @"";
    }
    NSString *urlString = [NSString stringWithFormat:@"http://api.miaotu.net/v2/%@/search?token=%@&keywords=%@&page=%ld&num=10", searchTypeString, tocken, _searchText.text, (long)_currentPage];
    NSDictionary *headerDic = @{@"User-Agent":@"Dalvik/1.6.0 (Linux; U; Android 4.3; R6007 Build/JLS36C) Paros/3.2.13", @"Host":@"api.miaotu.net", @"Connection":@"Keep-Alive"};
    [ZWYNetTool GET:urlString andBody:nil andHeader:headerDic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        
        if (_searchType == SearchTypeYueyou) {
            TravelModel *travelModel = [TravelModel modelWithDic:result];
            for (TravelItem *item in travelModel.Items) {
                [self.travelItemArray addObject:item];
            }
        } else {
            ConcernAndFan *cafModel = [ConcernAndFan modelWithDic:result];
            for (UserInfo *item in cafModel.Items) {
                [self.userInfoArray addObject:item];
            }
        }
        
        [_tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    } andFailureBlock:^(NSError *error) {
        
    }];
}

#pragma mark - CollectionView DataSource, Delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _citys.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HotPlaceCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kHotPlaceCollectionCell forIndexPath:indexPath];
    cell.cityLabel.text = _citys[indexPath.item];
    cell.layer.cornerRadius = 17;
    cell.layer.masksToBounds = YES;
    cell.layer.borderColor = [UIColor colorWithWhite:0.706 alpha:1.000].CGColor;
    cell.layer.borderWidth = 1;
    cell.cityLabel.backgroundColor = [UIColor colorWithWhite:0.976 alpha:1.000];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    _searchText.text = _citys[indexPath.item];
    _tableView.hidden = NO;
    [self createTableData];
}

#pragma mark - TableView DataSource, Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_searchType == SearchTypeYueyou) {
        return _travelItemArray.count;
    } else {
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_searchType == SearchTypeYueyou) {
        return 1;
    } else {
        return _userInfoArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_searchType == SearchTypeYueyou) {
        TravelTableCell *cell = [tableView dequeueReusableCellWithIdentifier:kTravelTableCell];
        if (cell == nil) {
            cell = [[TravelTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kTravelTableCell];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
//        cell.location = self.location;
        cell.travelItem = _travelItemArray[indexPath.section];
        cell.delegate = self;
        return cell;
    } else {
        SearchPersonTableCell *cell = [tableView dequeueReusableCellWithIdentifier:kSearchPersonTableCell forIndexPath:indexPath];
        cell.userInfo = _userInfoArray[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 350;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_searchType == SearchTypeYueyou) {
        TravelTableCell *cell = (TravelTableCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
        CGRect rect = [cell.rootLayout estimateLayoutRect:CGSizeMake(tableView.frame.size.width, 0)];
        return rect.size.height;
    } else {
        return 83;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_searchType == SearchTypeYueyou) {
        LineDetailViewController *lineDetailVC = [[LineDetailViewController alloc] init];
        lineDetailVC.yid = _travelItemArray[indexPath.section].Yid;
        self.navigationController.navigationBar.hidden = NO;
        [self.navigationController pushViewController:lineDetailVC animated:YES];
    } else {
        NSLog(@"users点击");
    }
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [_searchText endEditing:YES];
    _chooseTriangleImage.hidden = YES;
    _chooseView.hidden = YES;
}

#pragma mark - TextField Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length == 0) {
        return NO;
    }
    [textField endEditing:YES];
    _tableView.hidden = NO;
    [self createTableData];
    return YES;
}


#pragma mark - Action

- (void)ceateLocationManager {
    self.locManager = [CLLocationManager new];
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务还未打开");
        return;
    }
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [_locManager requestWhenInUseAuthorization];
    } else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
        
        self.locManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locManager.distanceFilter = 50;
        self.locManager.delegate = self;
        [self.locManager startUpdatingLocation];
    }
}


- (IBAction)cancel:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (IBAction)chooseSearchType:(UITapGestureRecognizer *)sender {
    _chooseTriangleImage.hidden = !_chooseTriangleImage.hidden;
    _chooseView.hidden = !_chooseView.hidden;
}

- (IBAction)searchLine:(id)sender {
    _searchTypeLabel.text = @"线路";
    _chooseTriangleImage.hidden = YES;
    _chooseView.hidden = YES;
    if (_searchText.text.length > 0) {
        [self createTableData];
    }
}

- (IBAction)searchPerson:(id)sender {
    _searchTypeLabel.text = @"人";
    _chooseTriangleImage.hidden = YES;
    _chooseView.hidden = YES;
    if (_searchText.text.length > 0) {
        [self createTableData];
    }
}

- (void)sendUid:(NSString *)uid {
    PersonalHomeViewController *perHomeVC = [[PersonalHomeViewController alloc] init];
    perHomeVC.Uid = uid;
    [self.navigationController pushViewController:perHomeVC animated:YES];
}

- (void)sendPicArrayAndImageUrl:(NSDictionary *)dic {
    
}

- (void)sendLRJMsgDic:(NSDictionary *)msgDic {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
